package cc.ufinity.networkdiagnose.app;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import cc.ufinity.networkdiagnose.manager.DBManager;
import cc.ufinity.networkdiagnose.manager.FTPConfig;
import cc.ufinity.networkdiagnose.manager.FtpTestManager;

public class App extends Application { 
	private Activity ctx;
	private FtpTestManager fm;
	private String path;
	private String localPath;
	private String remotePath;
	private CrashHandler crashHandler;
	
	public App(Context context) {
		ctx = (Activity) context;
		try {
			/*path = Environment.getExternalStorageDirectory().getAbsolutePath();
			localPath = path + "/NetworkDiagnose_LOG/";
			remotePath = "/log/";*/
			
			path = ctx.getFilesDir().getParent();
			localPath = path + File.separator + "log" + File.separator;
			remotePath = File.separator + "log" + File.separator;
			
			File fileDir = new File(localPath);
			//fileDir.mkdir();
			List<String> fileNames = new ArrayList<String>();
			File children[] = fileDir.listFiles() ;
			String fileName;
			for(int i=0; i<children.length; i++) {
				fileName = children[i].getName();
				if(fileName.endsWith(".log")); {
					fileNames.add(fileName);
				}
			}
			upload(fileNames);
		} catch (Exception e) { }
		
		crashHandler = CrashHandler.getInstance(); 
		crashHandler.init(context.getApplicationContext()); 
	}
	
	//文件上传
    private void upload(final List<String> fileNames) { 
    	new Thread() {
    		public void run() {
    			try {
					sleep(1000 * 60 * 10);
				} catch (Exception e) {}
    			try {
					DBManager db = new DBManager(ctx);
	    	        final FTPConfig ftp = db.getFtp();
	    	        db.release();
	    	        if (ftp != null && ftp.userName != null && ftp.userName.length() > 0) {
	    				fm = new FtpTestManager(localPath, remotePath, "");
	    	        	int port = ftp.port;
	    	            if (fm.login(ftp.address, port, ftp.userName, ftp.password)) {
	    	            	File file;
	    	            	for(String fileName:fileNames) {
	    	            		fm.setFileName(fileName);
	    	            		fm.upload();
	    	            		file = new File(localPath + fileName);
	    	                    if (file.exists()) {
	    	                        file.delete();
	    	                    }
	    	            	}
	    	            }
	    	        } 
				} catch (Exception e) {}
				finally {
					try{
						fm.logout();
					}catch (Exception e) {
						
					}
				}
    		}
    	}.start();
    } 
}